package com.yonyou.brigade.facade.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.enums.ChannelModel;
import com.yonyou.brigade.basic_init.enums.OpenTypeEnum;
import com.yonyou.brigade.basic_init.model.*;
import com.yonyou.brigade.basic_init.service.*;
import com.yonyou.brigade.facade.model.ChannelDTO;
import com.yonyou.brigade.facade.service.IAsyncService;
import com.yonyou.brigade.facade.service.IOpenService;
import com.yonyou.brigade.service.IBrigadePublicService;
import com.yonyou.brigade.third_parties.common.model.BriIconTenantDTO;
import com.yonyou.brigade.third_parties.common.service.IBriIconTenantService;
import com.yonyou.brigade.third_parties.didi.service.IDiDiCompanyService;
import com.yonyou.brigade.third_parties.smectrip.service.ISmeCtripPublicService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.JsonUtils;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.result.BasicResult;
import com.yonyou.ybzboot.starter.common.util.BeanUtils2;
import com.yonyou.ybzboot.starter.facade.result.FacadeResult;
import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.starter.mail.service.IMailService;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Description: 友商旅开通服务实现类
 * @since 2018/9/18
 */
@Service
public class OpenServiceImpl implements IOpenService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IMailService mailService;

    @Autowired
    @Qualifier("developerServiceImpl")
    private IDeveloperService developerService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("smeCtripPublicServiceImpl")
    private ISmeCtripPublicService smeCtripPublicService;

    @Autowired
    private IAsyncService asyncService;

    @Autowired
    private IDiDiCompanyService diDiCompanyService;

    @Autowired
    private IUserCenterService userCenterService;

    @Autowired
    private IBriChannelBaseService briChannelBaseService;

    @Autowired
    private IBriIconTenantService briIconTenantService;

    @Autowired
    private IBriSysConfigService briSysConfigService;

    @Autowired
    private IBriChannelAccountService briChannelAccountService;

    @Value("${brigade.cur}")
    private String curEnv;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Value("${ybz.queryOrgs.url}")
    private String queryOrgsUrl;

    @Value("${ybz.queryTenantInfo.url}")
    private String queryTenantInfo;

    /**
     * @Description: 商旅服务初始化
     * 1.邮件通知相关人员开通服务
     * @since 2018/9/18
     */
    @Override
    public Map openBrigade(String tenant) {
        Map<String, Object> result = new HashedMap();
        List<BriChannel> briChannelList = briChannelService.getEnableChannelByTenantAndChannel(tenant, "rtpnr");
        if (briChannelList != null && briChannelList.size() > 0) {
            result.put("status", 1);
            result.put("message", "OPEN");
        } else {
            sendOpenEmail(tenant);
            result.put("status", 1);
            result.put("message", "ONOPEN");
        }
        return result;
    }

    /**
     * @param channelDTO
     * @description: 友报账开通商旅服务
     * @since 2019-02-25
     */
    @Override
    public BasicResult open(ChannelDTO channelDTO) {
        Integer openType = channelDTO.getOpenType();
        //前端参数传错兼容
        if (channelDTO.getIsPreApprove() == null) {
            channelDTO.setIsPreApprove(Integer.valueOf(channelDTO.getConfig().get(ChannelDTO.IS_PRE_APPROVE).toString()));
        }
        if (openType == 2) {
            // 以组织进行开通
            List<RefModel> orgs = channelDTO.getOrgs();
            if (orgs == null || orgs.size() == 0) {
                return BasicResult.fail("2001001", "以组织类型开通时组织信息不能为空");
            } else {
                for (ChannelEnum channelEnum : ChannelEnum.values()) {
                    if (channelEnum.getName().equals(channelDTO.getChannel())) {
                        for (RefModel org : orgs) {
                            BriChannel briChannel = new BriChannel();
                            BeanUtils2.copyProperties(channelDTO, briChannel);
                            briChannel.setTenant(channelDTO.getTenantId());
                            briChannel.setPhone(channelDTO.getAdminPhone());

                            JSONObject config = JSONObject.parseObject(JSONObject.toJSONString(channelDTO.getConfig()));
                            /* 兼容之前的接口 */
                            if (channelEnum.equals(ChannelEnum.FANSCAR)) {
                                config.put("redundantDays", 0);
                            } else if (channelEnum.equals(ChannelEnum.CLYH)) {
                                config.put("version", "0.0.1");
                            }
                            briChannel.setConfig(config.toJSONString());
                            briChannel.setOrgpk(org.getId());
                            briChannel.setEnable(1);
                            briChannel.setCreateTime(new Date());
                            BriChannel old = briChannelService.getEnableChannelByPersonTenantOrgAndChannel(briChannel.getTenant(), briChannel.getOrgpk(), briChannel.getChannel());
                            if (old == null) {
                                briChannelService.insert(briChannel);
                            } else {
                                Wrapper<BriChannel> wrapper = new EntityWrapper<>();
                                wrapper.eq("id", old.getId());
                                briChannelService.update(briChannel, wrapper);
                            }
                        }
                        asyncService.syncDocInfo(channelDTO);
                        return BasicResult.success("商旅服务开通成功","商旅服务开通成功");
                    }
                }
                return BasicResult.fail("2001001", "暂不支持该商旅服务");
            }
        } else {
            // 以租户进行开通
            BriChannel briChannel = new BriChannel();
            BeanUtils2.copyProperties(channelDTO, briChannel);
            briChannel.setTenant(channelDTO.getTenantId());
            briChannel.setPhone(channelDTO.getAdminPhone());
            briChannel.setConfig(JSON.toJSONString(channelDTO.getConfig()));
            briChannel.setEnable(1);
            briChannel.setCreateTime(new Date());

            for (ChannelEnum channelEnum : ChannelEnum.values()) {
                if (channelEnum.getName().equals(briChannel.getChannel())) {
                    BriChannel old = briChannelService.getEnableChannelByPersonTenantOrgAndChannel(briChannel.getTenant(), briChannel.getOrgpk(), briChannel.getChannel());
                    if (old == null) {
                        // 携程商旅通自助开通
                        if (channelEnum.equals(ChannelEnum.CTRIPSME)) {
                            String tenantName = (String) channelDTO.getConfig().get("tenantName");
                            //默认开通提前审批
                            Integer isPreApprove = channelDTO.getIsPreApprove() == null ? 1 : channelDTO.getIsPreApprove();

                            JSONObject smeCtripConfig = smeCtripPublicService.autoRegisterCompany(channelDTO.getTenantId(), tenantName, isPreApprove);
                            channelDTO.setConfig(smeCtripConfig);
                            briChannel.setConfig(smeCtripConfig.toString());
                        } else if (channelEnum.equals(ChannelEnum.DIDI)) {
                            return open4DiDi(channelDTO.getTenantId(), channelDTO.getAdminPhone());
                        }
                        briChannelService.insert(briChannel);
                        asyncService.syncDocInfo(channelDTO);
                    }
                    return BasicResult.success("商旅服务开通成功","商旅服务开通成功");
                }
            }
            return BasicResult.fail("2001001", "暂不支持该商旅服务");
        }
    }

    @Override
    public JSONObject openStateList(HttpServletRequest request) {
        JSONObject dataJSON = new JSONObject();
        JSONObject resultJSON = new JSONObject();
        String tenantId = request.getParameter("tenantId");
        String userId = request.getParameter("userId");
        // 获取租户及管理员信息
        JSONObject tenantInfoJSON = getTenantInfo(tenantId);
        resultJSON.put("tenantInfo", tenantInfoJSON);

        //2.再判断商旅是否开通
        getThirdInfo(dataJSON, tenantId, userId);
        resultJSON.put("third", dataJSON);
        return resultJSON;
    }

    @Override
    public JSONObject queryConfig(JSONObject params) {
        JSONObject resultJSON = new JSONObject();
        String tenantId = params.getString("tenantId");
        String channel = params.getString("channel");
        Boolean isOpen = params.getBoolean("isOpen");
        JSONArray orgs = params.getJSONArray("orgs");
        BriChannelBase channelBase = briChannelBaseService.getBriChannelConfigByChannel(channel);
        JSONObject channelConfigJSON = new JSONObject();
        if (channelBase != null && !StringUtils.isEmpty(channelBase.getConfig())) {
            channelConfigJSON = JSONObject.parseObject(channelBase.getConfig());
            resultJSON.put("instruction", channelBase.getInstruction());
        }
        String sysConfigValueByKey = briSysConfigService.getSysConfigValueByKey("commonConfig", "common", "common");
        JSONObject sysConfigJSON = new JSONObject();
        if (!isOpen) {
            // 未开通的直接查询基础配置模板
            resultJSON.put("commonConfig", StringUtils.isEmpty(sysConfigValueByKey) ? new JSONObject() : JSONObject.parseObject(sysConfigValueByKey));
            resultJSON.put("channelConfig", channelConfigJSON);
        } else {
            // 已开通的需要将已存储的值赋给模板
            if (CollectionUtils.isEmpty(orgs)) {
                // 按租户开通
                sysConfigJSON = dealWithConfigIsOpenedByTenant(tenantId, channel, channelConfigJSON, sysConfigValueByKey, sysConfigJSON);
            } else {
                // 按组织开通
                sysConfigJSON = dealWithConfigIsOpenedByOrg(tenantId, channel, orgs, channelConfigJSON, sysConfigValueByKey, sysConfigJSON);
            }
            resultJSON.put("channelConfig", channelConfigJSON);
            resultJSON.put("commonConfig", sysConfigJSON);
        }
        return resultJSON;
    }

    private JSONObject dealWithConfigIsOpenedByOrg(String tenantId, String channel, JSONArray orgs, JSONObject channelConfigJSON, String sysConfigValueByKey, JSONObject sysConfigJSON) {
        BriChannel channelByOrg = briChannelService.getEnableInfoByTenantOrg(tenantId, orgs.getJSONObject(0).getString("id"), channel);
        if (channelByOrg != null) {
            //处理commonCofig
            if (!StringUtils.isEmpty(sysConfigValueByKey)) {
                sysConfigJSON = JSONObject.parseObject(sysConfigValueByKey);
                for (String key : sysConfigJSON.keySet()) {
                    JSONObject keyJSON = sysConfigJSON.getJSONObject(key);
                    JSONObject channelByTenantJSON = JSONObject.parseObject(JSON.toJSONString(channelByOrg));
                    keyJSON.put("value", channelByTenantJSON.get(key));
                    sysConfigJSON.put(key, keyJSON);
                }
            }
            //处理channelConfig
            JSONObject configJSON = JSONObject.parseObject(channelByOrg.getConfig());
            for (String key : channelConfigJSON.keySet()) {
                JSONObject jsonObject = channelConfigJSON.getJSONObject(key);
                jsonObject.put("value", configJSON.get(key));
                channelConfigJSON.put(key, jsonObject);
            }
        }
        return sysConfigJSON;
    }

    private JSONObject dealWithConfigIsOpenedByTenant(String tenantId, String channel, JSONObject channelConfigJSON, String sysConfigValueByKey, JSONObject sysConfigJSON) {
        BriChannel channelByTenant = briChannelService.getEnableChannelByOpenType(tenantId, channel, OpenTypeEnum.TENTANT.getIndex());
        if (channelByTenant != null) {
            //处理commonCofig
            if (!StringUtils.isEmpty(sysConfigValueByKey)) {
                sysConfigJSON = JSONObject.parseObject(sysConfigValueByKey);
                for (String key : sysConfigJSON.keySet()) {
                    JSONObject keyJSON = sysConfigJSON.getJSONObject(key);
                    JSONObject channelByTenantJSON = JSONObject.parseObject(JSON.toJSONString(channelByTenant));
                    keyJSON.put("value", channelByTenantJSON.get(key));
                }
            }
            //处理channelConfig
            JSONObject configJSON = JSONObject.parseObject(channelByTenant.getConfig());
            for (String key : channelConfigJSON.keySet()) {
                JSONObject jsonObject = channelConfigJSON.getJSONObject(key);
                jsonObject.put("value", configJSON.get(key));
                channelConfigJSON.put(key, jsonObject);
            }
        }
        return sysConfigJSON;
    }

    @Transactional
    @Override
    public JSONObject saveConfig(JSONObject params) {
        JSONObject resultJSON = new JSONObject();
        String tenantId = params.getString("tenantId");
        String userId = params.getString("userId");
        String phone = params.getString("phone");
        String channel = params.getString("channel");
        JSONArray orgs = params.getJSONArray("orgs");
        JSONObject config = params.getJSONObject("config");
        JSONObject channelConfig = config != null ? config.getJSONObject("channelConfig") : null;
        JSONObject commonConfig = config != null ? config.getJSONObject("commonConfig") : null;
        BriChannel briChannelOpened = null;
        if (CollectionUtils.isEmpty(orgs)) {
            List<BriChannel> channels = briChannelService.getEnableChannelByTenantAndChannel(tenantId, channel);
            if (!CollectionUtils.isEmpty(channels)) {
                briChannelOpened = channels.get(0);
            }
        } else {
            briChannelOpened = briChannelService.getEnableInfoByTenantOrg(tenantId, orgs.getJSONObject(0).getString("id"), channel);
        }
        if (StringUtils.isEmpty(tenantId) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(channel) || config == null || channelConfig == null || commonConfig == null) {
            throw new BusinessException("参数有误，请检查参数");
        }
        // 携程大客户处理bri_channel_account表
        if (ChannelEnum.CTRIPBC.getName().equals(channel)) {
            dealWithBriChannelAccount(tenantId, channelConfig);
        }
        // 更新
        if (briChannelOpened != null) {
            // 更新通用配置，渠道配置不允许更新
            dealWithCommonConfig(commonConfig, briChannelOpened);
            String configString = dealWithChannelConfig(briChannelOpened, channelConfig, channel, "update");
            String json = JSONObject.toJSONString(briChannelOpened);
            briChannelOpened.setConfig(configString);
            briChannelService.updateById(briChannelOpened);
            BriChannel briChannel = JSONObject.parseObject(json, BriChannel.class);
            asyncService.syncDisableStaffByOrg(briChannel, tenantId, briChannel.getOrgpk());
            resultJSON.put("success", Boolean.TRUE);
            return resultJSON;
        }
        // 新增
        List<BriChannel> briChannels = new ArrayList<>();
        BriChannel briChannel = new BriChannel();
        JSONObject smeCtripConfig = new JSONObject();
        if (CollectionUtils.isEmpty(orgs)) {
            // 按租户开通
            // 特殊处理滴滴、携程商旅通
            if (ChannelEnum.DIDI.getName().equalsIgnoreCase(channel)) {
                BasicResult basicResult = open4DiDi(tenantId, phone);
                if (basicResult.getData() != null && basicResult.getData() instanceof Map) {
                    return JSONObject.parseObject(JSON.toJSONString(basicResult.getData()));
                } else {
                    throw new BusinessException("滴滴企业版开通失败");
                }
            } else if (ChannelEnum.CTRIPSME.getName().equalsIgnoreCase(channel)) {
                String tenantName = params.getString("tenantName");
                //默认开通提前审批
                ChannelDTO channelDTO = JSONObject.parseObject(JSON.toJSONString(params), ChannelDTO.class);
                Integer isPreApprove = channelDTO.getIsPreApprove() == null ? 1 : channelDTO.getIsPreApprove();
                smeCtripConfig = smeCtripPublicService.autoRegisterCompany(channelDTO.getTenantId(), tenantName, isPreApprove);
            }
            BriChannel enableChannelByOpenType = briChannelService.getEnableChannelByOpenType(tenantId, channel, OpenTypeEnum.TENTANT.getIndex());
            if (enableChannelByOpenType != null) {
                briChannelService.deleteById(enableChannelByOpenType.getId());
            }
        } else {
            // 按组织开通（修改只能传一个组织，新增可以传多个组织）
            if (orgs.size() == 1) {
                BriChannel briChannelByOrg = briChannelService.getEnableInfoByTenantOrg(tenantId, orgs.getJSONObject(0).getString("id"), channel);
                if (briChannelByOrg != null) {
                    briChannelService.deleteById(briChannelByOrg.getId());
                }
            }
        }
        // 保存通用配置
        dealWithCommonConfig(commonConfig, briChannel);
        // 保存渠道配置
        String configString = "";
        configString = dealWithChannelConfig(briChannelOpened, channelConfig, channel, "add");
        briChannel.setConfig(configString);
        if (ChannelEnum.CTRIPSME.getName().equalsIgnoreCase(channel)) {
            briChannel.setConfig(smeCtripConfig.toString());
            // 默认开通预定前审批
            briChannel.setIsPreApprove(params.getInteger("isPreApprove") == null ? 1 : params.getInteger("isPreApprove"));
        }
        briChannel.setTenant(tenantId);
        briChannel.setEnable(1);
        briChannel.setPhone(phone);
        briChannel.setChannel(channel);
        briChannel.setCreateTime(new Date());
        if (CollectionUtils.isEmpty(orgs)) {
            briChannel.setOpenType(1);
            briChannelService.insert(briChannel);
        } else {
            briChannel.setOpenType(2);
            for (Object org : orgs) {
                JSONObject orgJSON = JSONObject.parseObject(JSON.toJSONString(org));
                BriChannel briChannelTemp = new BriChannel();
                BeanUtils2.copyProperties(briChannel, briChannelTemp);
                briChannelTemp.setOrgpk(orgJSON.getString("id"));
                briChannels.add(briChannelTemp);
            }
            briChannelService.insertBatch(briChannels);
        }
        // 同步人员部门职级等信息到第三方
        ChannelDTO channelDTO = new ChannelDTO();
        BeanUtils2.copyProperties(briChannel, channelDTO);
        channelDTO.setConfig(JSON.parseObject(briChannel.getConfig(), Map.class));
        channelDTO.setOrgs(JSONArray.parseArray(JSON.toJSONString(orgs), RefModel.class));
        channelDTO.setTenantId(tenantId);
        channelDTO.setAdminPhone(briChannel.getPhone());
        asyncService.syncDocInfo(channelDTO);
        resultJSON.put("success", Boolean.TRUE);
        return resultJSON;
    }

    private void dealWithBriChannelAccount(String tenantId, JSONObject channelConfig) {
        //防止不同租户使用同一个accountID，因为拉单时会根据accountID反查租户
        EntityWrapper<BriChannelAccount> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.where("account={0}", channelConfig.getJSONObject("accountID").getString("value"));
        entityWrapper1.and("enabled={0}", 1);
        List<BriChannelAccount> briChannelAccounts1 = briChannelAccountService.selectList(entityWrapper1);
        if (!CollectionUtils.isEmpty(briChannelAccounts1)) {
            if (!tenantId.equals(briChannelAccounts1.get(0).getTenant())) {
                throw new BusinessException(tenantId + "租户开通信息accountID：" + channelConfig.getJSONObject("accountID").getString("value") + "已被使用，请");
            }
        }
        EntityWrapper<BriChannelAccount> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("tenant={0}", tenantId);
        entityWrapper.and("account={0}", channelConfig.getJSONObject("accountID").getString("value"));
        entityWrapper.and("enabled={0}", 1);
        List<BriChannelAccount> briChannelAccounts = briChannelAccountService.selectList(entityWrapper);
        if (!CollectionUtils.isEmpty(briChannelAccounts)) {
            briChannelAccountService.delete(entityWrapper);
        }
        BriChannelAccount briChannelAccount = new BriChannelAccount();
        briChannelAccount.setTenant(tenantId);
        briChannelAccount.setAccount(channelConfig.getJSONObject("accountID").getString("value"));
        briChannelAccount.setAccountName(channelConfig.getJSONObject("accountName").getString("value"));
        //目前只有开通功能，默认传1，后续增加关闭功能，需前端传
        briChannelAccount.setEnabled(1);
        briChannelAccountService.insert(briChannelAccount);
    }

    /**
     * 第三方商旅服务关闭
     * @param params
     * @return
     */
    @Override
    public JSONObject closeChannel(JSONObject params) {
        JSONObject resultJSON = new JSONObject();
        String channel = params.getString("channel");
        String tenantId = params.getString("tenantId");
        JSONArray orgs = params.getJSONArray("orgs");
        List<BriChannel> briChannels = null;
        if (CollectionUtils.isEmpty(orgs)) {
            // 按租户开通
            briChannels = briChannelService.getEnableChannelByTenantAndChannel(tenantId, channel);
        } else {
            // 按组织开通
            briChannels = briChannelService.getEnableChannelByChannelAndOrgs(tenantId, orgs, channel);
        }
        if (!CollectionUtils.isEmpty(briChannels)) {
            for (BriChannel briChannel : briChannels) {
                briChannel.setEnable(0);
            }
            briChannelService.updateBatchById(briChannels);
        }
        resultJSON.put("success", Boolean.TRUE);
        return resultJSON;
    }

    /**
     * 处理渠道开通参数
     * @param channelConfig
     * @param channel
     * @param operateCode 操作编码：add 新开通；update 更新
     * @return
     */
    private String dealWithChannelConfig(BriChannel briChannel, JSONObject channelConfig, String channel, String operateCode) {
        String configString;
//        JSONObject configJSON = null;
        JSONObject channelConfigJSON = new JSONObject();
//        String config = briChannel.getConfig();
//        if (!StringUtils.isEmpty(config)) {
//            configJSON = JSONObject.parseObject(config);
//        }
        for (String key : channelConfig.keySet()) {
            JSONObject valueJSON = channelConfig.getJSONObject(key);
            if (valueJSON != null) {
                String value = valueJSON.getString("value");
//                if ("update".equals(operateCode) && configJSON != null) {
//
//                }
                channelConfigJSON.put(key, value);
            }
        }
        configString = JSON.toJSONString(channelConfigJSON);
        return configString;
    }

    private void dealWithCommonConfig(JSONObject commonConfig, BriChannel briChannel) {
        briChannel.setSyncUser(commonConfig.getJSONObject("syncUser") != null ? commonConfig.getJSONObject("syncUser").getInteger("value") : 0);
        briChannel.setSyncOrgDept(commonConfig.getJSONObject("syncOrgDept") != null ? commonConfig.getJSONObject("syncOrgDept").getInteger("value") : 0);
        briChannel.setSyncRank(commonConfig.getJSONObject("syncRank") != null ? commonConfig.getJSONObject("syncRank").getInteger("value") : 0);
        briChannel.setSsoKey(commonConfig.getJSONObject("ssoKey") != null ? commonConfig.getJSONObject("ssoKey").getInteger("value") : 0);
        briChannel.setIsPreApprove(commonConfig.getJSONObject("isPreApprove") != null ? commonConfig.getJSONObject("isPreApprove").getInteger("value") : 0);
        briChannel.setSyncCostInfo(commonConfig.getJSONObject("syncCostInfo") != null ? commonConfig.getJSONObject("syncCostInfo").getInteger("value") : 0);
        briChannel.setFromCityControl(commonConfig.getJSONObject("fromCityControl") != null ? commonConfig.getJSONObject("fromCityControl").getInteger("value") : 0);
        briChannel.setBookElasticDay(commonConfig.getJSONObject("bookElasticDay") != null ? commonConfig.getJSONObject("bookElasticDay").getInteger("value") : 0);
        briChannel.setRankSecondPass(commonConfig.getJSONObject("rankSecondPass") != null ? commonConfig.getJSONObject("rankSecondPass").getInteger("value") : 0);
        briChannel.setNoHotelOneDay(commonConfig.getJSONObject("noHotelOneDay") != null ? commonConfig.getJSONObject("noHotelOneDay").getInteger("value") : 0);
        briChannel.setHotelCityStrategy(commonConfig.getJSONObject("hotelCityStrategy") != null ? commonConfig.getJSONObject("hotelCityStrategy").getInteger("value") : 0);
        briChannel.setReimbursementPayByEnterprise((commonConfig.getJSONObject("reimbursementPayByEnterprise") != null && !StringUtils.isEmpty(commonConfig.getJSONObject("reimbursementPayByEnterprise").getString("value"))) ?
                commonConfig.getJSONObject("reimbursementPayByEnterprise").getJSONArray("value").toJSONString() : "");
        briChannel.setReimbursementPayBySelf((commonConfig.getJSONObject("reimbursementPayBySelf") != null && !StringUtils.isEmpty(commonConfig.getJSONObject("reimbursementPayBySelf").getString("value"))) ?
                commonConfig.getJSONObject("reimbursementPayBySelf").getJSONArray("value").toJSONString() : "");
        briChannel.setHotelReceptionPayBySelf(commonConfig.getJSONObject("hotelReceptionPayBySelf") != null ? commonConfig.getJSONObject("hotelReceptionPayBySelf").getInteger("value") : 1);
    }

    private void getThirdInfo(JSONObject dataJSON, String tenantId, String userId) {
        List<BriChannelBase> briChannelBases = briChannelBaseService.getBriChannelBases();
        if (CollectionUtils.isEmpty(briChannelBases)) {
            throw new BusinessException("请检查bri_channel_base预制数据");
        }
        for (BriChannelBase briChannelBase : briChannelBases) {
            JSONObject channelJSON = new JSONObject();
            String model = briChannelBase.getModel();
            channelJSON.put("tenantId", tenantId);
            channelJSON.put("model", model);
            channelJSON.put("sequence", briChannelBase.getSequence());
            channelJSON.put("channelName", briChannelBase.getChannelName());
            List<BriIconTenantDTO> briIcons = new ArrayList<>();
            if (ChannelEnum.CTRIPBC.getName().equals(briChannelBase.getChannelCode()) || ChannelEnum.CTRIPSME.getName().equals(briChannelBase.getChannelCode())) {
                briIcons = briIconTenantService.getIconsByChannelCode("ctrip", tenantId);
            } else {
                briIcons = briIconTenantService.getIconsByChannelCode(briChannelBase.getChannelCode(), tenantId);
            }
            channelJSON.put("icon", briIcons);
            switch (model) {
                case ChannelModel.JUMP:
                    dataJSON.put(briChannelBase.getChannelCode(), channelJSON);
                    break;
                case ChannelModel.TENANT:
                case ChannelModel.API:
                    BriChannel briChannel = briChannelService.getEnableChannelByOpenType(tenantId, briChannelBase.getChannelCode(), OpenTypeEnum.TENTANT.getIndex());
                    channelJSON.put("isOpen", briChannel != null ? true : false);
                    dataJSON.put(briChannelBase.getChannelCode(), channelJSON);
                    break;
                case ChannelModel.ORG:
                    JSONArray orgArray = new JSONArray();
                    String s = HttpClientUtil.doGet(ybzBaseUrl + queryOrgsUrl + "?tenantId=" + tenantId + "&userId=" + userId);
                    if (!StringUtils.isEmpty(s) && JsonUtils.isJSONArray(s)) {
                        orgArray = JSONArray.parseArray(s);
                    }
                    if (CollectionUtils.isEmpty(orgArray)) {
                        logger.info("查询开通信息时，该租户：" + tenantId + "未查询到组织信息");
                        continue;
                    }
                    List<BriChannel> briChannels = briChannelService.getEnableChannelByChannelAndOpenType(tenantId, briChannelBase.getChannelCode(), OpenTypeEnum.ORG.getIndex());
                    for (Object org : orgArray) {
                        JSONObject orgJSON = (JSONObject) org;
                        if (orgJSON.get("id") == null) {
                            continue;
                        }
                        orgJSON.put("isOpen", Boolean.FALSE);
                        if (!CollectionUtils.isEmpty(briChannels)) {
                            for (BriChannel channel : briChannels) {
                                if (orgJSON.getString("id").equals(channel.getOrgpk())) {
                                    orgJSON.put("isOpen", Boolean.TRUE);
                                    break;
                                }
                            }
                        }
                    }
                    channelJSON.put("orgs", orgArray);
                    dataJSON.put(briChannelBase.getChannelCode(), channelJSON);
                    break;
                case ChannelModel.BOTH:
                    dealWithBOTH(dataJSON, tenantId, userId, briChannelBase, channelJSON);
                    break;
                default:
                    break;
            }
        }
    }

    private void dealWithBOTH(JSONObject dataJSON, String tenantId, String userId, BriChannelBase briChannelBase, JSONObject channelJSON) {
        BriChannel channel = briChannelService.getEnableChannelByOpenType(tenantId, briChannelBase.getChannelCode(), OpenTypeEnum.TENTANT.getIndex());
        if (channel != null) {
            channelJSON.put("isOpen", Boolean.TRUE);
            channelJSON.put("openType", OpenTypeEnum.TENTANT.getIndex());
            dataJSON.put(briChannelBase.getChannelCode(), channelJSON);
            return;
        }
        List<BriChannel> briChannelList = briChannelService.getEnableChannelByChannelAndOpenType(tenantId, briChannelBase.getChannelCode(), OpenTypeEnum.ORG.getIndex());
        if (CollectionUtils.isEmpty(briChannelList)) {
            channelJSON.put("isOpen", Boolean.FALSE);
            channelJSON.put("openType", OpenTypeEnum.TENTANT.getIndex());
            if (dealWithOrgs(tenantId, userId, channelJSON, briChannelList)) return;
            dataJSON.put(briChannelBase.getChannelCode(), channelJSON);
            return;
        }
        channelJSON.put("openType", OpenTypeEnum.ORG.getIndex());
        if (dealWithOrgs(tenantId, userId, channelJSON, briChannelList)) return;
        dataJSON.put(briChannelBase.getChannelCode(), channelJSON);
        return;
    }

    private boolean dealWithOrgs(String tenantId, String userId, JSONObject channelJSON, List<BriChannel> briChannelList) {
        JSONArray orgArrays = new JSONArray();
        String s = HttpClientUtil.doGet(ybzBaseUrl + queryOrgsUrl + "?tenantId=" + tenantId + "&userId=" + userId);
        if (!StringUtils.isEmpty(s) && JsonUtils.isJSONArray(s)) {
            orgArrays = JSONArray.parseArray(s);
        }
        if (CollectionUtils.isEmpty(orgArrays)) {
            logger.info("查询开通信息时，该租户：" + tenantId + "未查询到组织信息");
            return true;
        }
        HashSet<String> openedOrgSet = new HashSet<>();
        for (BriChannel briChannel1 : briChannelList) {
            openedOrgSet.add(briChannel1.getOrgpk());
        }
        for (Object org : orgArrays) {
            JSONObject orgJSON = (JSONObject) org;
            if (orgJSON.get("id") == null) {
                continue;
            }
            if (openedOrgSet.contains(orgJSON.getString("id"))) {
                orgJSON.put("isOpen", Boolean.TRUE);
            } else {
                orgJSON.put("isOpen", Boolean.FALSE);
            }
        }
        channelJSON.put("orgs", orgArrays);
        return false;
    }

    private JSONObject getTenantInfo(String tenantId) {
        JSONObject tenantInfoJSON = new JSONObject();
        String result = HttpClientUtil.doGet(ybzBaseUrl + queryTenantInfo + "?tenantId=" + tenantId);
        if (StringUtils.isEmpty(result)) {
            return tenantInfoJSON;
        }
        return JSONObject.parseObject(result);
    }

    private BasicResult open4DiDi(String tenant, String phone) {
        String url = diDiCompanyService.getAutoAuthUrl(tenant, phone);
        if (url != null) {
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            return BasicResult.success(data);
        } else {
            return FacadeResult.failureWithMsg("获取滴滴授权地址失败");
        }
    }

    /**
     * @Description: 向相关人员发送邮件
     * @since 2018/9/18
     */
    private void sendOpenEmail(String tenant) {
        Email email = new Email();
        Wrapper<Developer> wrapper = new EntityWrapper<>();
        wrapper.eq("level", 1);
        List<Developer> developerList = developerService.selectList(wrapper);
        for (Developer developer : developerList) {
            String[] receiver = developer.getEmail().split(",");
            email.setEmail(receiver);
            email.setSubject("友商旅开通");
            String content = "亲爱的" + developer.getName() + ":  租户：" + tenant + "申请开通友商旅（中航易购）服务，请及时处理。";
            if (curEnv != null && curEnv.equals("prod")) {
                content += "--生产环境";
            } else {
                content += "--测试环境";
            }
            email.setContent(content);
            try {
                mailService.send(email);
            } catch (Exception e) {
                logger.error("友商旅开通邮件发送失败！邮件内容：" + email.toString(), e);
            }
        }
    }
}
